package com.itheima.restkeeper.face;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.restkeeper.AffixFace;
import com.itheima.restkeeper.UserFace;
import com.itheima.restkeeper.enums.UserEnum;
import com.itheima.restkeeper.exception.ProjectException;
import com.itheima.restkeeper.pojo.Role;
import com.itheima.restkeeper.pojo.User;
import com.itheima.restkeeper.req.AffixVo;
import com.itheima.restkeeper.req.UserVo;
import com.itheima.restkeeper.service.IUserAdapterService;
import com.itheima.restkeeper.service.IUserService;
import com.itheima.restkeeper.utils.BeanConv;
import com.itheima.restkeeper.utils.EmptyUtil;
import com.itheima.restkeeper.utils.ExceptionsUtil;
import com.itheima.restkeeper.utils.ResponseWrapBuild;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Method;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName UserFaceImpl.java
 * @Description 用户dubbo服务实现
 */
@Slf4j
@DubboService(version = "${dubbo.application.version}", timeout = 5000,
        methods = {
                @Method(name = "findUserVoPage", retries = 2),
                @Method(name = "createUser", retries = 0),
                @Method(name = "updateUser", retries = 0),
                @Method(name = "deleteUser", retries = 0)
        })
public class UserFaceImpl implements UserFace {

    @DubboReference(version = "${dubbo.application.version}", check = false)
    AffixFace affixFace;

    @Autowired
    IUserService userService;

    @Autowired
    IUserAdapterService userAdapterService;

    @Override
    public Page<UserVo> findUserVoPage(UserVo userVo,
                                       int pageNum,
                                       int pageSize) throws ProjectException {
        try {
            //查询用户分页
            Page<User> userVoPage = userService.findUserVoPage(userVo, pageNum, pageSize);
            //结果集转换
            Page<UserVo> voPage = new Page<>();
            BeanConv.toBean(userVoPage, voPage);
            List<User> records = userVoPage.getRecords();
            List<UserVo> userVos = BeanConv.toBeanList(records, UserVo.class);
            //处理附件
            if (!EmptyUtil.isNullOrEmpty(voPage) && !EmptyUtil.isNullOrEmpty(userVos)) {
                userVos.forEach(n -> {
                    List<AffixVo> affixVos = affixFace.findAffixVoByBusinessId(n.getId());
                    if (!EmptyUtil.isNullOrEmpty(affixVos)) {
                        n.setAffixVo(affixVos.get(0));
                    }

                    //处理角色,返回角色id的数组
                    List<Role> roles = userAdapterService.findRoleByUserId(userVo.getId());
                    ArrayList<String> roleIds = new ArrayList<>();
                    if (!EmptyUtil.isNullOrEmpty(roles)) {
                        for (Role role : roles) {
                            Long id = role.getId();
                            roleIds.add(String.valueOf(id));
                        }
                    }
                    //把集合转数组
                    String[] ids = new String[roleIds.size()];
                    roleIds.toArray(ids);
                    n.setHasRoleIds(ids);
                });
            }
            voPage.setRecords(userVos);
            //返回结果
            return voPage;
        } catch (Exception e) {
            log.error("查询用户列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.PAGE_FAIL);
        }
    }

    @Override
    public UserVo createUser(UserVo userVo) throws ProjectException {
        try {
            //保存用户
            User user = userService.createUser(userVo);
            //转换
            UserVo vo = BeanConv.toBean(user, UserVo.class);
            if (!EmptyUtil.isNullOrEmpty(user)) {
                //绑定附件
                AffixVo affixVo = affixFace.bindBusinessId(AffixVo.builder()
                        .businessId(user.getId())
                        .id(userVo.getAffixVo().getId())
                        .build());
                vo.setAffixVo(affixVo);
                //处理角色
                vo.setHasRoleIds(userVo.getHasRoleIds());
            }
            return vo;
        } catch (Exception e) {
            log.error("保存用户异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.CREATE_FAIL);
        }
    }

    @Override
    public Boolean updateUser(UserVo userVo) throws ProjectException {
        try {
            //修改用户
            Boolean boo = userService.updateUser(userVo);
            if (boo) {
                //删除图片
                List<AffixVo> affixVos = affixFace.findAffixVoByBusinessId(userVo.getId());
                ArrayList<Long> ids = new ArrayList<>();
                for (AffixVo affixVo : affixVos) {
                    ids.add(affixVo.getId());
                }
                if (!ids.contains(userVo.getAffixVo().getId())) {
                    //未绑定过
                    affixFace.deleteAffixVoByBusinessId(userVo.getId());
                    //绑定新图片
                    affixFace.bindBusinessId(AffixVo.builder()
                            .businessId(userVo.getId())
                            .id(userVo.getAffixVo().getId())
                            .build());
                }

            }
            return boo;
        } catch (Exception e) {
            log.error("保存用户异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.UPDATE_FAIL);
        }
    }

    @Override
    public Boolean deleteUser(String[] checkedIds) throws ProjectException {
        try {
            //删除用户
            Boolean boo = userService.deleteUser(checkedIds);
            //删除图片
            if (boo) {
                for (String checkedId : checkedIds) {
                    affixFace.deleteAffixVoByBusinessId(Long.valueOf(checkedId));
                }
            }
            return boo;
        } catch (Exception e) {
            log.error("删除用户异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.DELETE_FAIL);
        }
    }

    @Override
    public UserVo findUserByUserId(Long userId) throws ProjectException {
        try {
            //查找用户
            User user = userService.getById(userId);
            UserVo userVo = BeanConv.toBean(user, UserVo.class);
            //处理附件
            if (!EmptyUtil.isNullOrEmpty(userVo)) {
                List<AffixVo> affixVos = affixFace.findAffixVoByBusinessId(userVo.getId());
                if (!EmptyUtil.isNullOrEmpty(affixVos)) {
                    userVo.setAffixVo(affixVos.get(0));
                }
            }
            return userVo;
        } catch (Exception e) {
            log.error("查找用户所有角色异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.SELECT_USER_FAIL);
        }
    }

    @Override
    public List<UserVo> findUserVoList() throws ProjectException {
        try {
            //查找用户下拉框
            List<User> userVoList = userService.findUserVoList();
            List<UserVo> userVos = BeanConv.toBeanList(userVoList, UserVo.class);
            return userVos;
        } catch (Exception e) {
            log.error("查找用户list异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.SELECT_USER_LIST_FAIL);
        }
    }
}
